package com.wolfsea.defineviewgrouppaper.presenter
import com.wolfsea.defineviewgrouppaper.model.IModel
import com.wolfsea.defineviewgrouppaper.view.IView
import java.lang.ref.WeakReference
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

class BasePresenter<V : IView> : IPresenter<V> {

    private lateinit var weakView: WeakReference<V>
    protected lateinit var model: IModel
    protected lateinit var proxyView: V

    override fun attachView(view: V) {
        weakView = WeakReference(view)
        //使用动态代理防止重复写N个判断去检测接口是否为空
        val invocationHandler = MvpViewInvocationHandler(weakView.get() as V)
        proxyView = Proxy.newProxyInstance(
            view.javaClass.classLoader,
            view.javaClass.interfaces,
            invocationHandler
        ) as V
        Proxy.getProxyClass(view.javaClass.classLoader, *view.javaClass.interfaces)
    }

    override fun detachView() {
        weakView.clear()
    }

    fun isAttachView() = weakView.get() != null

    private inner class MvpViewInvocationHandler(mvpView: IView) : InvocationHandler {
        private val mView = mvpView
        override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
            if (isAttachView()) {
                return method?.invoke(mView, args)
            }
            return null
        }
    }

}